package com.wang.springbootinit.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.mapper.AnswerRecordMapper;
import com.wang.springbootinit.model.entity.*;
import com.wang.springbootinit.model.vo.AnswerRecordVO;
import com.wang.springbootinit.model.vo.QuestionVO;
import com.wang.springbootinit.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

@Service
public class AnswerRecordServiceImpl extends ServiceImpl<AnswerRecordMapper, AnswerRecord> implements AnswerRecordService {

    @Autowired
    private AnswerRecordMapper answerRecordMapper;

    @Autowired
    private ResearchChapterService researchChapterService;

    @Autowired
    private ResearchSubjectService researchSubjectService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private UserService userService;

    /**
     * 教师端获取学生做题记录
     * @param studentId 学生ID
     * @param subjectId 科目ID
     * @param chapterId 章节ID
     * @return
     */
    @Override
    public List<AnswerRecordVO> getStudentAnswerRecords(Long studentId, Long subjectId, Long chapterId) {
        LambdaQueryWrapper<AnswerRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AnswerRecord::getStudentId, studentId);
        List<AnswerRecord> answerRecords = list(queryWrapper);
        if(CollectionUtils.isEmpty(answerRecords)){
            return new ArrayList<>();
        }

        ResearchChapter chapter = researchChapterService.getById(chapterId);
        if(ObjectUtil.isNull(chapter)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        List<Question> questionList = questionService.getByChapterId(chapterId);
        List<QuestionVO> questionVOS = listQuestionVOByList(questionList);
        if(CollectionUtils.isEmpty(questionVOS)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        Map<Long, QuestionVO> questionMap = questionVOS.stream().collect(toMap(QuestionVO::getId, Function.identity(), (k1, k2) -> k1));
        Set<Long> questionIds = questionMap.keySet();


        return answerRecords.stream()
                .filter(item -> questionIds.contains(item.getQuestionId()))
                .map(item -> {
                    AnswerRecordVO recordVO = new AnswerRecordVO();
                    BeanUtils.copyProperties(item,recordVO);
                    recordVO.setQuestion(questionMap.get(recordVO.getQuestionId()));
                    return recordVO;
                }).collect(Collectors.toList());
    }

    /**
     * 教师端-批改学生题目
     * @param recordId 答题记录ID
     * @param isCorrect 是否正确
     * @return
     */
    @Override
    public Boolean correctStudentAnswer(Long recordId, Boolean isCorrect) {
        if(ObjectUtil.isNull(recordId) || ObjectUtil.isNull(isCorrect)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        AnswerRecord answerRecord = getById(recordId);
        if(ObjectUtil.isNull(answerRecord)){
            throw new BusinessException("题目不存在");
        }
        answerRecord.setIsCorrect(isCorrect);
        return updateById(answerRecord);
    }

    /**
     * 学生端-做题记录分页列表
     * @param chapterId
     * @param questionType 问题类型
     * @param questionCategory 问题分类
     * @param current
     * @param pageSize
     * @param request
     * @return
     */
    @Override
    public Page<AnswerRecordVO> getStudentQuestionPage(Long chapterId, Integer questionType, Integer questionCategory, long current, long pageSize, HttpServletRequest request) {
        Student loginStudent = userService.getLoginStudent(request);
        
        // 创建分页对象
        Page<AnswerRecord> page = new Page<>(current, pageSize);
        
        // 获取分页数据
        Page<AnswerRecord> recordPage = answerRecordMapper.getStudentQuestionPage(page, loginStudent.getId(), chapterId, questionType, questionCategory);
//        Page<AnswerRecord> recordPage = page(page, queryWrapper);
        List<AnswerRecord> records = recordPage.getRecords();
        
        if (CollectionUtils.isEmpty(records)) {
            return new Page<>();
        }
        
        // 获取所有问题记录ID
        Set<Long> questionIds = records.stream()
                .map(AnswerRecord::getQuestionId)
                .collect(Collectors.toSet());
        
        // 查询问题信息
        LambdaQueryWrapper<Question> questionWrapper = new LambdaQueryWrapper<>();
        questionWrapper.in(Question::getId, questionIds)
                .eq(ObjectUtil.isNotNull(chapterId),Question::getChapterId, chapterId)
                .eq(questionType != null, Question::getQuestionType, questionType)
                .eq(questionCategory != null, Question::getQuestionCategory, questionCategory);
        
        List<Question> questionList = questionService.list(questionWrapper);
        List<QuestionVO> questionVOS = listQuestionVOByList(questionList);
        Map<Long, QuestionVO> questionMap = questionVOS.stream()
                .collect(toMap(QuestionVO::getId, Function.identity(), (k1, k2) -> k1));
        
        // 转换为VO对象
        Page<AnswerRecordVO> answerRecordVOPage = new Page<>(current, pageSize, recordPage.getTotal());
        List<AnswerRecordVO> answerRecordVOList = records.stream()
                .map(record -> {
                    AnswerRecordVO vo = new AnswerRecordVO();
                    BeanUtils.copyProperties(record, vo);
                    vo.setQuestion(questionMap.get(record.getQuestionId()));
                    return vo;
                })
                .filter(vo -> vo.getQuestion() != null)
                .collect(Collectors.toList());
        
        answerRecordVOPage.setRecords(answerRecordVOList);
        return answerRecordVOPage;
    }

    /**
     * 学生端-删除答题记录
     * @param id 答题记录id
     * @param request
     * @return
     */
    @Override
    public Boolean deleteAnswerRecord(Long id, HttpServletRequest request) {
        Student loginStudent = userService.getLoginStudent(request);
        LambdaQueryWrapper<AnswerRecord> queryWrapper = new LambdaQueryWrapper<AnswerRecord>()
                .eq(AnswerRecord::getId, id)
                .eq(AnswerRecord::getStudentId, loginStudent.getId());
        return remove(queryWrapper);
    }

    @Override
    public Page<AnswerRecordVO> getStudentErrorQuestionPage(Long chapterId, Integer questionType, Integer questionCategory, long current, long pageSize, HttpServletRequest request) {
        Student loginStudent = userService.getLoginStudent(request);

        // 创建分页对象
        Page<AnswerRecord> page = new Page<>(current, pageSize);

        // 获取分页数据
        Page<AnswerRecord> recordPage = answerRecordMapper.getStudentErrorQuestionPage(page, loginStudent.getId(), chapterId, questionType, questionCategory);
//        Page<AnswerRecord> recordPage = page(page, queryWrapper);
        List<AnswerRecord> records = recordPage.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            return new Page<>();
        }

        // 获取所有问题记录ID
        Set<Long> questionIds = records.stream()
                .map(AnswerRecord::getQuestionId)
                .collect(Collectors.toSet());

        // 查询问题信息
        LambdaQueryWrapper<Question> questionWrapper = new LambdaQueryWrapper<>();
        questionWrapper.in(Question::getId, questionIds)
                .eq(ObjectUtil.isNotNull(chapterId),Question::getChapterId, chapterId)
                .eq(questionType != null, Question::getQuestionType, questionType)
                .eq(questionCategory != null, Question::getQuestionCategory, questionCategory);

        List<Question> questionList = questionService.list(questionWrapper);
        List<QuestionVO> questionVOS = listQuestionVOByList(questionList);
        Map<Long, QuestionVO> questionMap = questionVOS.stream()
                .collect(toMap(QuestionVO::getId, Function.identity(), (k1, k2) -> k1));

        // 转换为VO对象
        Page<AnswerRecordVO> answerRecordVOPage = new Page<>(current, pageSize, recordPage.getTotal());
        List<AnswerRecordVO> answerRecordVOList = records.stream()
                .map(record -> {
                    AnswerRecordVO vo = new AnswerRecordVO();
                    BeanUtils.copyProperties(record, vo);
                    vo.setQuestion(questionMap.get(record.getQuestionId()));
                    return vo;
                })
                .filter(vo -> vo.getQuestion() != null)
                .collect(Collectors.toList());

        answerRecordVOPage.setRecords(answerRecordVOList);
        return answerRecordVOPage;
    }

    public List<QuestionVO> listQuestionVOByList(List<Question> list){
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }

        List<Long> chapterIds = list.stream().map(Question::getChapterId).collect(Collectors.toList());
        List<ResearchChapter> chapterList = researchChapterService.listByIds(chapterIds);
        Map<Long, ResearchChapter> chapterMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(chapterList)){
            chapterMap = chapterList.stream().collect(toMap(ResearchChapter::getId, Function.identity(), (k1, k2) -> k1));
        }

        List<Long> subjectIds = chapterList.stream().map(ResearchChapter::getSubjectId).collect(Collectors.toList());
        List<ResearchSubject> researchSubjects = researchSubjectService.listByIds(subjectIds);
        Map<Long, ResearchSubject> subjectMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(researchSubjects)){
            subjectMap = researchSubjects.stream().collect(toMap(ResearchSubject::getId, Function.identity(), (k1, k2) -> k1));
        }

        Map<Long, ResearchChapter> finalChapterMap = chapterMap;
        Map<Long, ResearchSubject> finalSubjectMap = subjectMap;
        return list.stream().map(item -> {
            QuestionVO questionVO = new QuestionVO();
            BeanUtils.copyProperties(item,questionVO);
            ResearchChapter chapter = finalChapterMap.get(item.getChapterId());
            if(ObjectUtil.isNotNull(chapter)){
                questionVO.setChapterId(chapter.getId());
                questionVO.setChapterName(chapter.getChapterName());
                ResearchSubject subject = finalSubjectMap.get(chapter.getSubjectId());
                if(ObjectUtil.isNotNull(subject)){
                    questionVO.setSubjectName(subject.getSubjectName());
                    questionVO.setSubjectId(subject.getId());
                }
            }
            return questionVO;
        }).collect(Collectors.toList());

    }

} 